package org.lewis.woman.controllers;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.lewis.common.store.OSSUtils;
import org.lewis.common.utils.WebUtils;

import com.tocersoft.framework.core.annotations.Controller;
import com.tocersoft.framework.core.utils.PropertiesUtils;
import com.tocersoft.framework.web.annotations.Mapping;
import com.tocersoft.framework.web.annotations.NameSpace;
import com.tocersoft.framework.web.renderer.Renderer;
import com.tocersoft.framework.web.renderer.TextRenderer;


@Controller
@NameSpace("/admin/picture/")
public class PictureUploadController {
	
	
	private final static String UPLOAD_SUCCESS = "1000";// 成功
	private final static String UNKNOWN_MEMTHOD = "1";// 不支持的方法
	private final static String FILE_ISNULL = "2";// 未上传文件
	private final static String FILE_TO_LONG = "3";// 文件过大
	private final static String FILE_UNKNOWN_EXT = "4";// 文件格式错误
	
	private Log log = LogFactory.getLog(SongUploadController.class);
	
	@Mapping("/upload")
	@SuppressWarnings("unchecked")
	public Renderer upload() throws Exception {
		
		Long start=System.currentTimeMillis();
		JSONObject msg = new JSONObject();

		// 方法校验
		if (!WebUtils.isPost()) {
			msg.put("code", UNKNOWN_MEMTHOD);
			msg.put("msg", "不支持的上传方法");
			return new TextRenderer(msg.toString());
		}

		// 处理上传
		HttpServletRequest request = WebUtils.getRequest();
		int maxMemorySize = Integer.parseInt(PropertiesUtils.getValue("uploaded.maxMemorySize"));
		long maxRequestSize = Long.parseLong(PropertiesUtils.getValue("uploaded.songSize"));
		FileItem item = null;
		
		String tag="covers";//默认模块
		
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(maxMemorySize);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(maxRequestSize);
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem ft : items) {
				if (!ft.isFormField()) {
					item = ft;
					break;
				}else{
					//设置图片模块
					String name = item.getFieldName();
					if("tag".equals(name)){
						if(StringUtils.isNotBlank(item.getString())){
							tag= item.getString();
						}
					}
				}
			}
		} catch (Exception e) {
			// 文件过大
			msg.put("code", FILE_TO_LONG);
			msg.put("msg", "文件大小不能超多10MB");
			return new TextRenderer(msg.toString());
		}

		// 校验是否上传了文件
		if (item == null || (item != null && item.getSize() == 0)) {
			msg.put("code", FILE_ISNULL);
			msg.put("msg", "请上传文件");
			return new TextRenderer(msg.toString());
		}

		// 文件格式校验
		String allowExt = PropertiesUtils.getValue("allow.image.ext");
		String[] allowExts = allowExt.toLowerCase().split(",");
		String ext = StringUtils.substringAfterLast(item.getName(), ".")
				.toLowerCase();
		if (!ArrayUtils.contains(allowExts, ext)) {
			msg.put("code", FILE_UNKNOWN_EXT);
			msg.put("msg", "不支持的文件格式");
			return new TextRenderer(msg.toString());
		}

		// 上传临时目录
		String tempDir = PropertiesUtils.getValue("static.upload.tempdir")+ "/common/pic/" + UUID.randomUUID().toString();
		String absDir = WebUtils.getRealyPath(tempDir);
		File absDirs = new File(absDir);
		if (!absDirs.exists()) {
			absDirs.mkdirs();
		}

		// 生成文件名
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String objectName = sdf.format(new Date()) + "_"+ UUID.randomUUID().toString() + "." + ext;
		InputStream in = null;
		OutputStream out = null;
		try {
			File file = new File(WebUtils.getRealyPath(tempDir + "/"
					+ objectName));
			in = item.getInputStream();
			out = new BufferedOutputStream(new FileOutputStream(file),
					maxMemorySize);
			byte[] buffer = new byte[maxMemorySize];
			int length = 0;
			while ((length = in.read(buffer)) != -1) {
				out.write(buffer, 0, length);
			}
			OSSUtils.storeCommonPic(file, objectName, tag);
			FileUtils.deleteQuietly(file);
		} catch (Exception e) {
			log.error("图片上传失败:"+e.getMessage());
			msg.put("msg", "上传失败");
			return new TextRenderer(msg.toString());
		} finally {
			IOUtils.closeQuietly(in);
			IOUtils.closeQuietly(out);
			FileUtils.deleteDirectory(absDirs);
		}
		msg.put("code", UPLOAD_SUCCESS);
		msg.put("objectName", objectName);
		msg.put("tag", tag);
		msg.put("url", tag+"/"+objectName);
		msg.put("fileName", StringUtils.substringBefore(item.getName(), "."));
		msg.put("msg", "上传成功");
		
		Long end=System.currentTimeMillis();
		
		log.info("图片上传一共耗时:"+(end-start)/1000+"秒");
		
		return new TextRenderer(msg.toString());

	}

	

}
